package com.example.javaproject.controller;

import com.example.javaproject.common.R;
import com.example.javaproject.service.UserExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/api/user/excel")
public class UserExcelController {
    @Autowired
    private UserExcelService userExcelService;

    @GetMapping("/export")
    public void exportUsers(HttpServletResponse response) {
        try {
            userExcelService.exportUsers(response);
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/import")
    public R importUsers(@RequestParam("file") MultipartFile file) {
        try {
            int successCount = userExcelService.importUsers(file);
            return R.ok("成功导入 " + successCount + " 条数据");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("导入失败：" + e.getMessage());
        }
    }

    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            userExcelService.downloadTemplate(response);
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
} 